import 'package:flutter/material.dart';
import '../utils/flutter_communication.dart';

class UserListPage extends StatefulWidget {
  @override
  _UserListPageState createState() => _UserListPageState();
}

class _UserListPageState extends State<UserListPage> {
  List<Map<String, dynamic>> users = [];
  String deviceInfo = 'Loading...';
  bool isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadData();
    _listenToNativeEvents();
  }

  Future<void> _loadData() async {
    setState(() {
      isLoading = true;
    });

    try {
      // 获取设备信息
      final deviceInfoResult = await FlutterCommunication.getDeviceInfo();
      
      // 获取用户数据
      final usersResult = await FlutterCommunication.getUsers();

      setState(() {
        deviceInfo = deviceInfoResult;
        users = usersResult;
        isLoading = false;
      });
    } catch (e) {
      setState(() {
        deviceInfo = 'Error: $e';
        isLoading = false;
      });
    }
  }

  void _listenToNativeEvents() {
    // 延迟一点时间确保Android端EventChannel已经设置完成
    Future.delayed(Duration(milliseconds: 500), () {
      try {
        FlutterCommunication.nativeEvents.listen(
          (event) {
            print('Received event from native: $event');
            // 处理来自原生的事件
            if (event is Map && event['type'] == 'userUpdated') {
              _loadData(); // 重新加载数据
            }
          },
          onError: (error) {
            print('Error listening to native events: $error');
          },
        );
      } catch (e) {
        print('Error setting up event listener: $e');
      }
    });
  }

  Future<void> _sendDataToNative() async {
    try {
      await FlutterCommunication.sendDataToNative('Hello from Flutter!');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Data sent to native!')),
      );
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Error sending data: $e')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('User List'),
        actions: [
          IconButton(
            icon: Icon(Icons.refresh),
            onPressed: _loadData,
          ),
          IconButton(
            icon: Icon(Icons.send),
            onPressed: _sendDataToNative,
          ),
        ],
      ),
      body: isLoading
          ? Center(child: CircularProgressIndicator())
          : Column(
              children: [
                // 设备信息卡片
                Card(
                  margin: EdgeInsets.all(16),
                  child: Padding(
                    padding: EdgeInsets.all(16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          'Device Info',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        SizedBox(height: 8),
                        Text(deviceInfo),
                      ],
                    ),
                  ),
                ),
                // 用户列表
                Expanded(
                  child: users.isEmpty
                      ? Center(
                          child: Text('No users found'),
                        )
                      : ListView.builder(
                          itemCount: users.length,
                          itemBuilder: (context, index) {
                            final user = users[index];
                            return ListTile(
                              leading: CircleAvatar(
                                child: Text(user['name']?[0] ?? 'U'),
                              ),
                              title: Text(user['name'] ?? 'Unknown'),
                              subtitle: Text(user['email'] ?? ''),
                              onTap: () {
                                Navigator.pushNamed(
                                  context,
                                  '/userDetails',
                                  arguments: user,
                                );
                              },
                            );
                          },
                        ),
                ),
              ],
            ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.pushNamed(context, '/addUser');
        },
        child: Icon(Icons.add),
        tooltip: 'Add User',
      ),
    );
  }
}
